﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;

namespace Ruandao.MiniFace
{
    public class ExternalListWidget : ListWidgetBase
    {
        public ExternalListWidget()
        {
        }

        protected override List<KeyValuePair<string, dynamic>> VariablesToPython(TemplateContext templateContext, out dynamic dataList)
        {
            var list = new List<KeyValuePair<string, dynamic>>();
            dynamic widgetArgs = new System.Dynamic.ExpandoObject();

            // 必填参数：BaseAddress
            string baseAddressArg;
            if (!Properties.TryGetValue("BaseAddress", out baseAddressArg))
            {
                throw new Exception("ExternalDetails微件必须设置BaseAddress属性。");
            }
            widgetArgs.BaseAddress = baseAddressArg;

            // 必填参数：Url
            string urlArg;
            if (!Properties.TryGetValue("Url", out urlArg))
            {
                throw new Exception("ExternalDetails微件必须设置Url属性。");
            }
            widgetArgs.Url = urlArg;

            // 可选DataName参数，默认为"DataList"。
            string dataNameArg = "DataList";
            if (Properties.ContainsKey("DataName")) dataNameArg = Properties["DataName"];
            widgetArgs.DataName = dataNameArg;

            // 可选参数：GroupNumber， 默认为1，表示不使用分组呈现。
            if (Properties.ContainsKey("GroupNumber")) this.GroupNumber = int.Parse(Properties["GroupNumber"]);
            widgetArgs.GroupNumber = this.GroupNumber;

            // 可选参数：IdName，默认为""，表示不使用当前项模板。
            if (Properties.ContainsKey("IdName")) this.IdName = Properties["IdName"];
            widgetArgs.IdName = this.IdName;

            // 可选参数：CurrentId，默认为""，表示不使用当前项模板。
            if (Properties.ContainsKey("CurrentId")) this.CurrentId = Properties["CurrentId"];
            widgetArgs.CurrentId = this.CurrentId;

            // 其他查询参数，请求Url时放到查询字符串中。
            var webClient = new WebClient();
            webClient.BaseAddress = baseAddressArg;
            foreach (var kv in Properties)
            {
                if (kv.Key == "Url" || kv.Key == "BaseAddress") continue;
                ((IDictionary<string,object>)widgetArgs).Add(kv.Key, kv.Value);
                webClient.QueryString.Add(kv.Key, kv.Value);
            }
            list.Add(new KeyValuePair<string, dynamic>("WidgetArgs", widgetArgs));

            webClient.Encoding = System.Text.Encoding.UTF8;
            string json = webClient.DownloadString(urlArg);
            dataList = JsonConvert.DeserializeObject(json);
            list.Add(new KeyValuePair<string, dynamic>(dataNameArg, dataList));

            return list;
        }
    }
}
